import {BasePage, BasePageData} from "../common/core/BasePage";
import {DataLoader, field} from "../../modules/coreModule/data/DataLoader";
import {Trade} from "../../modules/payModule/data/Trade";
import {BaseData, PK} from "../../modules/coreModule/data/BaseData";
import {page, pageFunc} from "../common/PageBuilder";
import {ItemDetailPage} from "../common/pages/ItemDetailPage";
import {waitForLogin} from "../../modules/userModule/managers/UserManager";
import {PayInterface} from "../../modules/payModule/PayCommon";
import {Bill} from "../../modules/payModule/data/Bill";
import {pageMgr} from "../../modules/coreModule/managers/PageManager";
import {PaymentPage} from "../payment/PaymentPage";
import {Contract} from "../../modules/payModule/data/Contract";

class Data extends BasePageData {

	// @field(Trade)
	// item: Trade;

	@field(Trade)
	trade: Trade;
	@field(Contract)
	contract: Contract;
}

class Param extends BaseData {
	tradeId?: PK
	contractId?: PK
	onSuccess?: () => any
}

@page("payResult", "支付结果")
export class PayResultPage extends BasePage<Data, Param> {

	public data = new Data();
	// public params: {
	// 	id: PK,
	// 	nextPage: string,
	// 	nextParams: any
	// }

	onLoad(e) {
		super.onLoad(e);
		this.loadData().then();
	}

	@waitForLogin
	private async loadData() {

		const tRes = await PayInterface.GetTrade({tradeId: this.params.tradeId});

		let trade, contract;
		if (tRes.trade) {
			trade = DataLoader.load(Trade, tRes.trade);
			trade.bill = DataLoader.load(Bill, tRes.bill);
		} else { // 优先获取Trade，没有再展示Contract
			const cRes = await PayInterface.GetContract({contractId: this.params.contractId});
			if (cRes.contract)
				contract = DataLoader.load(Contract, cRes.contract);
		}

		await this.setData({ trade, contract })

		// const res = await PayInterface.GetTrade({tradeId: this.params.id});
		// const trade = DataLoader.load(Trade, res.trade);
		// trade.bill = DataLoader.load(Bill, res.bill);
		//
		// return this.setItem(trade);
	}

	// region 事件

	/**
	 * 支付
	 */
	@pageFunc
	public pay() {
		pageMgr().change(PaymentPage, this.params)
	}

	/**
	 * 确定
	 */
	@pageFunc
	public confirm() {
		this.params.onSuccess ? this.params.onSuccess() : this.back();
	}

	// endregion
}
